package com.mysterymall.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Comp.LocalCache;
import com.mysterymall.Common.Comp.Log;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.Result;
import com.mysterymall.Model.Dto.SmsDto;
import com.mysterymall.Service.SmsService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @ClassName com.mysterymall.Controller
 * @Description
 * @Author HuangWX
 * @Time 2023/11/29  09:39
 */
@RestController
@RequestMapping("/sms")
public class SmsCont {


    private final SmsService smsService;

    /**
     * 构造器注入
     * @param smsService 短信服务
     */
    public SmsCont(SmsService smsService) {
        this.smsService = smsService;
    }

    @PostMapping("/sendVerify")
    @Log
    public Result sendSms(@RequestBody SmsDto smsDto,HttpServletRequest request) throws IOException {

        // 获取HttpSession
        HttpSession session = request.getSession();

        // 获取Session ID
        String sessionId = session.getId();

        // 防止恶意刷图
        if(LocalCache.CACHE.get(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId) != null){
            int count = (int) LocalCache.CACHE.get(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId);
            if(count > 15){
                return new Result(HttpStatus.BAD_NOT_PASS,"message.queryError");
            }else {
                return smsService.sendSms(smsDto,sessionId);
            }
        }else{
            LocalCache.CACHE.put(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId,1,60 * 1000 * 60);
        }

        return new Result(HttpStatus.BAD_NOT_PASS,"message.queryError");

    }


    /**
     * 获取验证码图片
     * @param response 响应
     * @throws IOException 异常
     */
    @GetMapping("/turingTest")
    @Log
    public Result verify(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取HttpSession
        HttpSession session = request.getSession();

        // 获取Session ID
        String sessionId = session.getId();

        // 防止恶意刷图
        if(LocalCache.CACHE.get(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId) != null){
            int count = (int) LocalCache.CACHE.get(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId);
            if(count > 15){
                return new Result(HttpStatus.BAD_NOT_PASS,"message.queryError");
            }else {
                LocalCache.CACHE.put(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId,count+1,60 * 1000 * 60);
            }
        }else{
            LocalCache.CACHE.put(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId,1,60 * 1000 * 60);
        }

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建图形验证码
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(150, 40, 5, 3);

        // 将验证码写入 ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        shearCaptcha.write(outputStream);

        // 将 ByteArrayOutputStream 中的数据转换为 Base64 字符串
        String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());

        // 打印验证码
        System.out.println("验证码: "+shearCaptcha.getCode());

        // 在这里将验证码存储到缓存或 Session 中，以便后续验证
        LocalCache.CACHE.put(BaseEnum.Turing_Test_Image.getCode()+sessionId,shearCaptcha.getCode(),60 * 1000);

        // 关闭流
        outputStream.close();

        return Result.success("message.querySuccess",base64Image);
    }


    @GetMapping("/turingTestCode")
    @Log
    public Result verifyCode(@RequestParam("code") String code,HttpServletRequest request){

        // 获取HttpSession
        HttpSession session = request.getSession();

        // 获取Session ID
        String sessionId = session.getId();

        // 防止恶意刷图
        if(LocalCache.CACHE.get(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId) != null){
            int count = (int) LocalCache.CACHE.get(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId);
            if(count > 15){
                return new Result(HttpStatus.BAD_NOT_PASS,"message.queryError");
            }
        }else{
            LocalCache.CACHE.put(BaseEnum.Turing_Test_Get_Restrict.getCode()+sessionId,1,60 * 1000 * 60);
        }

        // 获取验证码
        String sessionCode = (String) LocalCache.CACHE.get(BaseEnum.Turing_Test_Image.getCode()+sessionId);

        // 验证码校验
        if(sessionCode != null && sessionCode.equals(code)){
            return Result.success("message.querySuccess");
        }else {
            return new Result(HttpStatus.BAD_NOT_PASS,"message.queryError");
        }
    }

}
